package io.netty.example.http.websocketx.client.chatclient;

import com.alibaba.fastjson.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.example.http.websocketx.common.entity.NettyMessage;
import io.netty.example.http.websocketx.common.util.ByteObjConvert;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Description
 * @Author fuguangli businessfgl@163.com
 * @Create date:    2017/9/26
 */
public class ChatClient {
    public static void main(String[] args) throws Exception {
        new ChatClient("127.0.0.1", 9090).run();
    }

    private final String host;
    private final int port;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer());
            Channel channel = bootstrap.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            NettyMessage message = new NettyMessage();
            for(int i=0;i>-1;i++){

//                message.setMessage(in.readLine());
//                channel.writeAndFlush(message);


                String msg = "第一次被实例化且使用完毕后";
                message.setMessage(msg);
                channel.writeAndFlush(ByteObjConvert.wrapMsg(JSON.toJSONString(message)));
                System.out.println("消息包大小="+ByteObjConvert.wrapMsg(JSON.toJSONString(message)).length);

                Thread.sleep(100);
//            in.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }
}

